import { Component, OnInit } from '@angular/core';

declare var jBinary;
@Component({
  selector: 'app-hex-editor',
  templateUrl: './hex-editor.component.html',
  styleUrls: ['./hex-editor.component.css']
})
export class HexEditorComponent implements OnInit {

  rows = 32;
  cols = Math.floor(window.innerHeight / 20 - 2);
  offset;
  binary;
  // 当前位置
  current;
  items = [];
  positions = [];

  constructor() { }

  ngOnInit() {
    this.loadItems()
  }

  /**
   * 转为16进制显示
   * @param number unit8
   * @param length 
   */
  toHex(number, length) {
    var s = number.toString(16).toUpperCase();
    while (s.length < length) {
      s = '0' + s;
    }
    return s;
  };

  /**
   * 以字符显示
   * @param number 
   */
  toChar(number) {
    return number <= 32 ? ' ' : String.fromCharCode(number);
  }

  loadFromFile(file) {
    jBinary.loadData(file, function (err, data) {
      this.binary = new jBinary(data);
      // document.querySelector('.tmp').style.height = this.binary.view.byteLength / this.rows * 20 + 250 + 'px';
      this.offset = this.current = 0;
      this.loadItems();
    });
  };

  loadItems() {
    var data = "hello here is nnn"
    var result = [];

    for (var i = 0; i < data.length; i += 2) {
      result.push(parseInt(data.substring(i, i + 2), 16));
    }
    var ary = Uint8Array.from(result)
    // 数据
    this.items = [];
    // 位置
    this.positions = [];
    for (var a in ary) {
      if (typeof data[a] !== 'object' && typeof data[a] !== 'function')
        this.items.push(data[i]);
    }
    for (var c = 0; c < this.cols; c += 1) {
      this.positions.push(this.toHex(this.offset + c * 32, 8));
    }
    console.log(this.positions);
    //this.$apply();
  };

  setCurrent(index) {
    this.current = index;
  };

}
